package tcplib

import (
	"cow_golang/shared_mod/tcplib/iface"
	"fmt"
)

type MessageHandles struct {
	//id 和处理方法对应的 map
	Handles map[uint32]iface.IHandle
}

func (s *MessageHandles) AddHandle(msgId uint32, handle iface.IHandle) {
	// 前置检查id是否已经增加了
	if _, ok := s.Handles[msgId]; ok {
		return
	}
	// 增加协议和处理
	s.Handles[msgId] = handle
	fmt.Println("add msg id:", msgId, ", 对应的handle")
}

func (s *MessageHandles) AddAllHandles(handles map[uint32]iface.IHandle) {
	s.Handles = handles
	fmt.Println("add all msg id 对应的handle")
}

func NewMessageHandle() *MessageHandles {
	return &MessageHandles{
		Handles: make(map[uint32]iface.IHandle),
	}
}

// 具体处理消息的实现
func (s *MessageHandles) CallMessageHandle(request iface.IRequest) {
	handle, ok := s.Handles[request.GetID()]
	if !ok {
		fmt.Println("handle message id:", request.GetID(), " is not found")
		return
	}
	// aop
	handle.PreHandle(request)
	handle.Handle(request)
	handle.PostHandle(request)
}
